const puppeteer = require('puppeteer-core');
const fs = require('fs');
const path = require('path');
const { sleep, randomInt, getSongIdFromUrl} = require('./Helper')
const Download = require("./Download");
const Config = require("./Config");
const IgnoreSong = require('./IgnoreSong')
//从页面获取各种信息
class MusicPage
{

    /** 从网易云页面获取 frame元素
     * @param {import('puppeteer-core').Page} page - Puppeteer 页面对象
     * @param {string} selector 选择器
     * @return {Promise<Frame|null>}
     */
    static async getFrame(page,selector = '#g_iframe') {
        const iframeHandle = await page.$(selector);
        return await iframeHandle.contentFrame();
    }

    /**
     * @param {import('puppeteer-core').Page} page - Puppeteer 页面对象
     * @return {Promise<array[{url,title,name}]>}
     */
    static async getAlbumSongs(page)
    {
        const frame = await MusicPage.getFrame(page);

        const selector = '[id^="auto-id-"] .even .f-cb a';
        console.log('等 3秒，加载一下');
        await sleep(3000);
        const songs = await frame.evaluate((selector) => {
            const els = document.querySelectorAll(selector);
            const songs = [];
            for (const ele of els) {
                const title = ele.querySelector('b').title;
                //'爱在西元前 - (电视剧《丑女大翻身》片头曲)';
                const name = title.split(' - ')[0];
                songs.push({
                    url : ele.href,
                    title : title,
                    name : name.replace(/\u00A0/g, ' ').trim(),
                });
            }
            return songs;
        },selector);
        return songs;
    }

    /**
     * @param {import('puppeteer-core').Page} page - Puppeteer 页面对象
     * @return {Promise<array|null>}
     */
    static async getAlbums(page)
    {
        const frame = await MusicPage.getFrame(page);
        const selector = '#m-song-module > li > p.dec.dec-1.f-thide2.f-pre > a';
        const albums = await frame.evaluate((selector) => {
            const els = document.querySelectorAll(selector);
            const albums = [];
            for (let i = 0; i < els.length; i++) {
                albums.push({
                    title : els[i].innerText,
                    url : els[i].href
                });
            }
            return albums;
        },selector);
        return albums;
    }

    /**
     * @param {import('puppeteer-core').Page} page - Puppeteer 页面对象
     * @return {Promise<string|null>}
     */
    static async getUserUrl(page) {

        const frame = await MusicPage.getFrame(page);
        const selector = '#discover-module > div.g-sd1 > div.n-user-profile > div > div > a';
        const userUrl = await frame.evaluate((selector) => {
            const el = document.querySelector(selector);
            return el ? el.href : null;
        }, selector);
        return userUrl
    }

    /** 获取用户的所有歌单 url
     * @param {import('puppeteer-core').Page} userPage - Puppeteer 页面对象
     * @return {Promise<array|null>}
     */
    static async getPlayListUrls(userPage)
    {
        const frame = await MusicPage.getFrame(userPage);
        const selector = '#sBox [id^="auto-id-"] > p > a, #cBox [id^="auto-id-"] > p > a';
        //遍历   '#cBox [id^="auto-id-"] > p > a'  的 href;
        const playListUrls = await frame.evaluate((selector) => {
            const els = document.querySelectorAll(selector);
            const urls = [];
            for (let i = 0; i < els.length; i++) {
                if (els[i].href) {
                    urls.push(els[i].href);
                }
            }
            return urls;
        },selector);
        return playListUrls
    }

    /** 获取歌单的歌曲urls
     * @param {import('puppeteer-core').Page} playListPage - Puppeteer 页面对象
     * @return {Promise<array|null>}
     */
    static async getMusicUrls(playListPage)
    {
        const frame = await MusicPage.getFrame(playListPage);
        // 表格行选择器，支持动态 id
        const tableRowSelector = '[id^="auto-id-"] .m-table tbody > tr';

        // 在 iframe 中遍历表格行，获取第二列的 a.href 和 b.title
        const rowsData = await frame.evaluate((selector) => {
            const rows = document.querySelectorAll(selector);
            const data = [];

            for (const row of rows) {
                const td = row.querySelectorAll('td')[1]; // 第二个 td
                if (!td) continue;

                const a = td.querySelector('a');
                const b = td.querySelector('b');

                const parsedUrl = new URL(a.href);
                const songId = parsedUrl.searchParams.get('id');

                data.push({
                    id : songId,
                    href: a ? a.href : null,
                    title: b ? b.title : null
                });
            }

            return data;
        }, tableRowSelector);
        return rowsData;
    }

    /**
     * 获取歌单下载地址
     * @param {import('puppeteer-core').Page} page - Puppeteer 页面对象
     * @return {Promise<string|null>} - 返回歌曲的真实播放URL 或 null
     */
    static async getMusicDownloadUrl(page)
    {
        const currentUrl = page.url();
        return new Promise(async (resolve, reject) => {
            let flag = false;
            let resultUrl = null;

            // 监听接口响应
            page.on('response', async (response) => {
                try {
                    const songUrl = response.url();
                    if (flag) return;

                    if (songUrl.includes('/weapi/song/enhance/player/url/v1')) {
                        await sleep(1000 + randomInt(100,500));
                        if (flag) return;
                        const data = await response.json();
                        if (data.data && data.data[0] && data.data[0].url) {
                            if (flag) return;
                            flag = true;
                            resultUrl = data.data[0].url;
                            console.log('✅ 捕获到真实播放URL:', resultUrl);
                            resolve(resultUrl);
                        }
                    }
                } catch (e) {
                    console.error('解析响应失败:', e);
                }
            });

            // 获取 frame 并尝试点击播放按钮
            const frame = await MusicPage.getFrame(page);
            await sleep(3000);

            const hasPlay = await frame.evaluate(() => {
                const disabled = document.querySelector('#content-operation > a.u-btni.u-btni-play.u-btni-play-dis');
                if (disabled) return 'disabled';
                const selectors = [
                    '#content-operation > div > a.u-btn2.u-btn2-2.u-btni-vipply.f-fl',
                    '#content-operation > a.u-btn2.u-btn2-2.u-btni-addply.f-fl',
                ];
                for (const selector of selectors) {
                    const element = document.querySelector(selector);
                    if (element) {
                        element.click();
                        return 'clicked';
                    }
                }
                return 'noBtn';
            });







            if (hasPlay === 'disabled') {
                console.log('🚫 这首歌不能播');
                IgnoreSong.ignoreByUrl(currentUrl,'这首歌不能播');
                resolve(null);
                return;
            }

            if (hasPlay === 'noBtn') {
                console.log('❌ 没有播放按钮');
                IgnoreSong.ignoreByUrl(currentUrl,'没有播放按钮');
                resolve(null);
                return;
            }

            let hasCopyRight = await frame.evaluate(() => !document.querySelector('[id^="auto-id-"] > div.lyct.f-tc > div > div.tip'));

            if (!hasCopyRight) {
                console.log('❌ 没版权');
                IgnoreSong.ignoreByUrl(currentUrl,'没版权');
                resolve(null);
                return;
            }

            // 等待网络请求响应
            console.log('⏳ 等待接口响应中...');
            await sleep(10000);

            if (!flag) {

                console.log('⚠️ 超时未获取到歌曲URL');
                resolve(null);
            }
        });
    }

    // async get()
    // {
    //     'https://music.163.com/#/artist/album?id=6452&limit=1000&offset=0'
    // }


}
module.exports = MusicPage;